let _Vue = null
export default class VueRouter {
  constructor (options) {
    this.options = options
    this.mode = options.mode || 'hash'
    if (this.mode === 'hash') {
      window.location.hash = '/'
    }
    // 响应式data,current 记录当前的路由地址,vue中自带的observable()可以创建一个响应式对象
    this.data = _Vue.observable({
      current: '/'
    })
    this.routeMap = {
      // 路由地址：路由组件
    }
  }

  static install (Vue) {
    // 1. 判断当前插件是否已经被安装，若安装则无需再安装
    // 我们给VueRouter install增加一个installed属性用来记录是否被安装
    if (VueRouter.install.installed) {
      return
    }
    VueRouter.install.installed = true
    // 2. 把vue构造函数记录到全局变量
    _Vue = Vue
    // 把创建vue实例时传入的router对象注入到Vue实例上
    _Vue.mixin({
      beforeCreate () {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init()
        }
      }
    })
  }

  createRouteMap () {
    // 遍历所以路由规则解析成键值对的形式存储到routeMap中，路由规则都存放在了options中的routes
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }

  initComponents (Vue) {
    Vue.component('router-link', {
      props: {
        to: String
      },
      render (h) {
        return h('a', {
          attrs: {
            href: this.to
          },
          on: {
            click: this.clickHandler
          }
        }, [this.$slots.default])
      },
      methods: {
        clickHandler (e) {
          if (this.mode === 'hash') {
            window.location.hash = `#${this.to}`
          } else {
            history.pushState({}, '', this.to)
          }
          this.$router.data.current = this.to
          e.preventDefault()
        }
      }
    })
    const that = this
    Vue.component('router-view', {
      render (h) {
        const com = that.routeMap[that.data.current]
        return h(com)
      }
    })
  }

  init () {
    this.createRouteMap()
    this.initComponents(_Vue)
    this.initEvent()
  }

  // 解决浏览器前进后退时地址栏发生变化但当前地址未变化的情况
  initEvent () {
    if (this.mode === 'hash') {
      window.addEventListener('hashchange', () => {
        this.data.current = location.hash.substr(1)
      })
    } else {
      window.addEventListener('popstate', () => {
        this.data.current = window.location.pathname
      })
    }
  }
}
